// IamPermissionStore.ts
import { defineStore } from 'pinia';
import type { Module } from './IamModuleStore';

// 导出 Permission 接口，供其他模块使用
export interface Permission {
  perm_id: number;
  perm_name: string;
  perm_code: string;
  perm_type: number;
  module_id?: number;
  perm_desc?: string;
  create_time?: string;
  update_time?: string;
  is_active?: number;
  is_deleted?: number;
  sort_order?: number;
  description?: string;
}

// 定义 API 响应类型
export interface PermissionResponse {
  code: number;
  data: Permission[];
  message: string;
  total: number;
}

// 定义分页参数接口
export interface PermissionQueryParams {
  page: number;
  pageSize: number;
  perm_name?: string;
  perm_code?: string;
  module_id?: string;
  perm_type?: string;
  is_active?: string;
}

export const useIamPermissionStore = defineStore('iamPermission', {
  state: () => ({
    permissionList: [] as Permission[],
    totalCount: 0,
    loading: false,
  }),

  actions: {
    // 获取权限列表
    async fetchPermissionList(params: PermissionQueryParams) {
      this.loading = true;
      try {
        // 这里应该是实际的 API 调用
        // const response = await api.get<PermissionResponse>('/permissions', params);
        // 模拟数据
        const response: PermissionResponse = {
          code: 200,
          data: [
            {
              perm_id: 1,
              perm_name: '用户管理',
              perm_code: 'user.manage',
              perm_type: 1,
              module_id: 1,
              perm_desc: '用户管理权限',
              create_time: '2023-01-01',
              update_time: '2023-01-01',
              is_active: 1,
              sort_order: 1
            }
          ],
          message: 'success',
          total: 1
        };

        this.permissionList = response.data;
        this.totalCount = response.total;
      } catch (error) {
        console.error('获取权限列表失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 添加权限
    async addPermission(permission: Omit<Permission, 'perm_id'>) {
      try {
        // 这里应该是实际的 API 调用
        // const response = await api.post<Permission>('/permissions', permission);
        // 模拟数据
        const newPermission: Permission = {
          perm_id: Date.now(), // 模拟 ID 生成
          ...permission
        };

        this.permissionList.push(newPermission);
        this.totalCount += 1;
      } catch (error) {
        console.error('添加权限失败:', error);
        throw error;
      }
    },

    // 更新权限
    async updatePermission(id: number, permission: Partial<Permission>) {
      try {
        // 这里应该是实际的 API 调用
        // const response = await api.put<Permission>(`/permissions/${id}`, permission);
        // 模拟数据
        const index = this.permissionList.findIndex(p => p.perm_id === id);
        if (index !== -1) {
          this.permissionList[index] = { ...this.permissionList[index], ...permission };
        }
      } catch (error) {
        console.error('更新权限失败:', error);
        throw error;
      }
    },

    // 删除权限
    async deletePermission(id: number) {
      try {
        // 这里应该是实际的 API 调用
        // await api.delete(`/permissions/${id}`);
        // 模拟数据
        this.permissionList = this.permissionList.filter(p => p.perm_id !== id);
        this.totalCount -= 1;
      } catch (error) {
        console.error('删除权限失败:', error);
        throw error;
      }
    },

    // 批量删除权限
    async batchDeletePermissions(ids: number[]) {
      try {
        // 这里应该是实际的 API 调用
        // await api.post('/permissions/batch-delete', { ids });
        // 模拟数据
        this.permissionList = this.permissionList.filter(p => !ids.includes(p.perm_id));
        this.totalCount -= ids.length;
      } catch (error) {
        console.error('批量删除权限失败:', error);
        throw error;
      }
    },
  },
});